package swing;

import misc.Utils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

public class DialogMenuItem extends JMenuItem implements ActionListener {
    /**
     *
     */
    private static final long serialVersionUID = 2466871711987100605L;
    private Class<? extends Dialog> dialogClass;
    private Object[] initArgs;
    private Dialog dialog;

    public DialogMenuItem(final Class<? extends Dialog> dialogClass, final Object... initArgs) {
        super(Utils.createName(dialogClass, "Dialog"));
        this.dialogClass = dialogClass;
        this.initArgs = initArgs;

        addActionListener(this);
    }

    public DialogMenuItem(Dialog dialog) {
        super(Utils.createName(dialog.getClass(), "Dialog"));
        this.dialog = dialog;

        addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (dialog == null) {
            java.util.List<Class<?>> types = new ArrayList<>();
            for (Object arg : initArgs)
                types.add(arg.getClass());

            try {
                Constructor<? extends Dialog> constructor = dialogClass.getConstructor(types.toArray(new Class[types.size()]));
                dialog = constructor.newInstance(initArgs);
            } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e1) {
                e1.printStackTrace();
            }
        }

        dialog.setVisible(true);
    }
}
